/* PexifTool - $Revision$
 * Copyright (C) 2011 Petros Dolaschjan.  All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *  THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 *  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 *  ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
 *  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 *  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 *  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 *  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *	$Id$
 */
package de.pd.pjim2.controller.gui.dialog;

import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

import org.jdesktop.application.Application;
import org.jdesktop.application.Task;
import org.jdesktop.swingx.JXTable;
import org.jdesktop.swingx.decorator.HighlighterFactory;

import com.thebuzzmedia.imgscalr.Scalr;

import de.pd.pjim2.bean.PJFolderChangesBean;
import de.pd.pjim2.bean.PJImageFile;
import de.pd.pjim2.controller.PJWindowController;

/**
 * @author petros
 * 
 */
public class ChangesPreviewDialog extends JDialog implements
		ListSelectionListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2556704584845678150L;

	private TableModel tableModel = new DefaultTableModel();
	private PJFolderChangesBean mChangesBean;
	private JLabel imgLabel;

	public ChangesPreviewDialog(Frame pParent, PJFolderChangesBean pChangesBean) {
		super(pParent, true);
		mChangesBean = pChangesBean;
		setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
		String title = pChangesBean.getTotalChanges() + " Changes" + " in "
				+ pChangesBean.getDirName();
		setTitle(title);
		setMinimumSize(new Dimension(800, 400));

		getContentPane().setLayout(new GridBagLayout());
		GridBagConstraints gbc = new GridBagConstraints();
		gbc.fill = GridBagConstraints.HORIZONTAL;

		JPanel panelImgPrev = new JPanel();
		panelImgPrev.setPreferredSize(new Dimension(200, 10));
		// panelImgPrev.setBackground(Color.blue);
		panelImgPrev.setLayout(new FlowLayout(FlowLayout.CENTER));
		imgLabel = new JLabel("");
		panelImgPrev.add(imgLabel);

		// gbc.weightx = 0.25;
		gbc.fill = GridBagConstraints.VERTICAL;
		gbc.weighty = 1;
		gbc.gridx = 0;
		gbc.gridy = 0;
		getContentPane().add(panelImgPrev, gbc);

		// JPanel panel = new JPanel();

		// full path panel
		JPanel panelPath = new JPanel();
		panelPath.setLayout(new FlowLayout(FlowLayout.LEFT));
		JLabel lblPath = new JLabel("Source Dir: ");
		JTextField tfPath = new JTextField(pChangesBean.getDir());
		tfPath.setBorder(null);
		tfPath.setOpaque(false);
		tfPath.setEditable(false);
		panelPath.add(lblPath);
		panelPath.add(tfPath);
		// add(panelPath);

		// TABLE
		List<PJImageFile> images = pChangesBean.getImages();
		String[][] objects = new String[images.size()][5];
		String[] cols = new String[] { "Original File", "Target File",
				"Rotate", "Dest. Dir" };

		for (int row = 0; row < images.size(); row++) {
			PJImageFile img = images.get(row);
			objects[row][0] = img.getSrcFile().getName();
			objects[row][1] = img.getDstFile().getName();
			objects[row][2] = String.valueOf(img.isDoRotate() ? "Yes" : "No");
			objects[row][3] = img.getDstFile().getParentFile().getName();
		}
		tableModel = new DefaultTableModel(objects, cols);

		JXTable table = new JXTable(tableModel);
		table.setEditable(false);
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		table.setHorizontalScrollEnabled(true);
		table.setColumnControlVisible(true);
		table.setShowGrid(true);
		table.setHighlighters((HighlighterFactory.createSimpleStriping()));
		table.setVisibleRowCount(5);
		table.setAutoResizeMode(JXTable.AUTO_RESIZE_ALL_COLUMNS);
		table.packAll();

		table.addMouseListener(new MouseAdapter() {

			@Override
			public void mouseClicked(MouseEvent pEvt) {
				super.mouseClicked(pEvt);

				if (pEvt.getClickCount() == 2) {
					JTable target = (JTable) pEvt.getSource();
					int row = target.getSelectedRow();
					String fname = (String) tableModel.getValueAt(row, 0);
					File imgFile = new File(mChangesBean.getDir()
							+ File.separator + fname);
					showImage(imgFile);
				}
			}
		});

		ListSelectionModel selectionModel = table.getSelectionModel();
		selectionModel.addListSelectionListener(this);

		// table.add^

		JScrollPane sp = new JScrollPane(table);

		gbc.fill = GridBagConstraints.BOTH;
		gbc.weighty = 1;
		gbc.weightx = 1;
		gbc.gridx = 1;
		gbc.gridy = 0;
		getContentPane().add(sp, gbc);
		pack();
	}

	/**
	 * Shows the image in a dialog.
	 * 
	 * @param pImgFile
	 */
	private void showImage(File pImgFile) {
		JDialog dia = new JDialog(this, true);
		dia.setTitle(pImgFile.getName());
		dia.setResizable(false);
		dia.setPreferredSize(new Dimension(600, 500));
		dia.getContentPane().setLayout(null);
		JLabel lblImage = new JLabel();
		lblImage.setBounds(0, 0, 200, 50);
		GenerateThumbTask gtt = new GenerateThumbTask(
				PJWindowController.getApplication(), pImgFile, 600, lblImage, dia);
		gtt.execute();
		dia.getContentPane().add(lblImage);
		dia.pack();
		dia.setLocationRelativeTo(this);
		dia.setVisible(true);

	}

	public class GenerateThumbTask extends Task<ImageIcon, Void> {

		private File imgFile;
		private int width;
		private JLabel targetLabel;
		private Container parentComp;

		
		/**
		 * @param pApplication
		 * @param pImgFile
		 */
		public GenerateThumbTask(Application pApplication, File pImgFile,
				int pWidth, JLabel pTargetLabel, Container pParentComp) {
			super(pApplication);
			imgFile = pImgFile;
			this.width = pWidth;
			targetLabel = pTargetLabel;
			parentComp = pParentComp;

			targetLabel.setIcon(null);
			targetLabel.setText("Loading...");
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see javax.swing.SwingWorker#doInBackground()
		 */
		@Override
		protected ImageIcon doInBackground() throws Exception {
			BufferedImage bi;
			try {
				bi = ImageIO.read(imgFile);
			} catch (IOException e) {
				e.printStackTrace();
				return null;
			}

			BufferedImage image = Scalr.resize(bi, Scalr.Method.SPEED, width,
					null);
			return new ImageIcon(image);
		}

		@Override
		protected void succeeded(ImageIcon pResult) {
			// TODO Auto-generated method stub
			super.succeeded(pResult);
			targetLabel.setText("");
			targetLabel.setIcon(pResult);
			targetLabel.setBounds(0, 0, pResult.getIconWidth(), pResult.getIconHeight());
			if(parentComp != null) {
				parentComp.setSize(new Dimension(pResult.getIconWidth(), pResult.getIconHeight()));
			}
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.swing.event.ListSelectionListener#valueChanged(javax.swing.event
	 * .ListSelectionEvent)
	 */
	@Override
	public void valueChanged(ListSelectionEvent pE) {
		if (pE.getValueIsAdjusting())
			return;
		ListSelectionModel lsm = (ListSelectionModel) pE.getSource();
		String fname = (String) tableModel.getValueAt(
				lsm.getLeadSelectionIndex(), 0);
		File imgFile = new File(mChangesBean.getDir() + File.separator + fname);
		GenerateThumbTask gtt = new GenerateThumbTask(
				PJWindowController.getApplication(), imgFile, 180, imgLabel, null);
		gtt.execute();
	}
}
